package at.irian.jsfatwork.broker.domain;

import javax.persistence.Transient;
import java.util.UUID;

/**
 * Abstract base class for all entities.
 * Provides equals and hashCode support for transient entities by means of a temporary GUID.
 *
 * @author Thomas Spiegl, IRIAN Solutions GmbH
 */
public abstract class BaseEntity {

    private String guid;

    public abstract Long getId();

    @Transient
    public boolean isTransient() {
        return getId() == null;
    }

    /**
     * Return a global unique id (GUID) for this entity.
     * If this entity is persistent the simple entity class name plus the entity id is returned.
     * For transient entities a random temporary GUID is created.
     * @return a GUID for this entity
     */
    @Transient
    public String getGuid() {
      if (this.guid == null) {
        if (getId() != null) {
          this.guid = this.getClass().getSimpleName() + "@" + getId();
        } else {
          this.guid = UUID.randomUUID().toString();
        }
      }
      return this.guid;
    }

    /**
     * Two entities are considered equal if
     * - they are both not null
     * - they are both instances of BaseEntity
     * - they both have the same GUID
     *
     * @param obj other BaseEntity
     * @return true if obj is equal to this
     */
    @Override
    public boolean equals(Object obj) {
      if (obj == null) return false;
      if (!(obj instanceof BaseEntity)) return false;
      BaseEntity that = (BaseEntity) obj;
      return this.getGuid().equals(that.getGuid());
    }

    /**
     * @return the hash code of the id property or 0 if this entity has no id yet
     */
    @Override
    public int hashCode() {
      return getGuid().hashCode();
    }


}
